package com.codermn.并发访问控制.guava令牌桶;

import com.google.common.util.concurrent.RateLimiter;

import java.time.LocalDateTime;

/**
 * <p>
 *     guava封装了非常简单的并发控制工具类RateLimiter，作为单机的并发控制首选
 *      一个控制qps为2的简单demo如下:
 * </p>
 * @author jxau_scf
 * @date 2021/8/13 - 14:26
 */
public class GuavaDemo {
    private void guavaProcess(RateLimiter rateLimiter){
        try {
            //同步阻塞方式获取
            System.out.println("准备执行： " + Thread.currentThread() + "  >  " + LocalDateTime.now());
            rateLimiter.acquire();
            System.out.println("执行中： " + Thread.currentThread() + "  >  " + LocalDateTime.now());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void testGuavaRate() throws InterruptedException {
        RateLimiter rateLimiter = RateLimiter.create(2.0d);

        new Thread(()->guavaProcess(rateLimiter)).start();
        new Thread(()->guavaProcess(rateLimiter)).start();
        new Thread(()->guavaProcess(rateLimiter)).start();
        new Thread(()->guavaProcess(rateLimiter)).start();
        new Thread(()->guavaProcess(rateLimiter)).start();
        new Thread(()->guavaProcess(rateLimiter)).start();
        new Thread(()->guavaProcess(rateLimiter)).start();

        Thread.sleep(20000);

    }
}
